
package com.luck.pf.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.luck.org.entity.SysUser;
import com.luck.pf.security.menu.logic.IMenuLogic;
import com.luck.pf.security.user.logic.IUserLogic;

/**
 * 说明: Copyright: Copyright (c) 2010
 * 可以从数据库中读入用户的密码，角色信息，是否锁定，账号是否过期等
 * @author zhangwenrui 2010-8-6 下午04:09:29
 * @version 1.0
 */
public class MyUserDetailService implements UserDetailsService {
	private IUserLogic userLogic;
	private IMenuLogic menuLogic;
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		SysUser person = userLogic.findUserByLoginname(username);
		List<Long> dbAuths = null;
		if(person == null)
			throw new UsernameNotFoundException("没有此用户");
		try {
			//得到用户所有的模块权限资源
			dbAuths = menuLogic.findUserAuth(username);
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataRetrievalFailureException("读取权限错误");
		}
		if(dbAuths == null || dbAuths.isEmpty())
			throw new DataRetrievalFailureException("["+username+"]用户没有任何权限");

		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		for(Long authId:dbAuths){
			GrantedAuthorityImpl auth = new GrantedAuthorityImpl(authId.toString());
			auths.add(auth);
		}
		boolean enabled = false;
		if(person.getEnabled()==1)
			enabled = true;
		User user = new User(username, person.getPassword(), enabled, true, true, true, auths);
		return user;
	}
	public IUserLogic getUserLogic() {
		return userLogic;
	}
	public void setUserLogic(IUserLogic userLogic) {
		this.userLogic = userLogic;
	}
	public IMenuLogic getMenuLogic() {
		return menuLogic;
	}
	public void setMenuLogic(IMenuLogic menuLogic) {
		this.menuLogic = menuLogic;
	}

}
